<template>
  <div class="user-manager">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <a-button type="primary" @click="showAddModal">
          <PlusOutlined />
          添加用户
        </a-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <a-card>
        <a-form :model="searchForm" layout="inline" @finish="handleSearch" class="search-form">
          <a-form-item label="用户账号" name="userAccount">
            <a-input
              v-model:value="searchForm.userAccount"
              placeholder="请输入用户账号"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="用户名" name="userName">
            <a-input
              v-model:value="searchForm.userName"
              placeholder="请输入用户名"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="邮箱" name="email">
            <a-input
              v-model:value="searchForm.email"
              placeholder="请输入邮箱"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="用户角色" name="userRole">
            <a-select
              v-model:value="searchForm.userRole"
              placeholder="请选择用户角色"
              allow-clear
              style="width: 150px"
            >
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
              <a-select-option value="vip">VIP用户</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                <SearchOutlined />
                搜索
              </a-button>
              <a-button @click="resetSearch">
                <ReloadOutlined />
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <a-card>
        <a-table
          :columns="columns"
          :data-source="userList"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
          :scroll="{ x: 1200 }"
        >
          <!-- 头像列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'userAvatar'">
              <a-avatar :src="record.userAvatar" :size="40">
                <template #icon><UserOutlined /></template>
              </a-avatar>
            </template>

            <!-- 用户角色列 -->
            <template v-else-if="column.key === 'userRole'">
              <a-tag :color="getRoleColor(record.userRole)">
                {{ getRoleText(record.userRole) }}
              </a-tag>
            </template>

            <!-- VIP状态列 -->
            <template v-else-if="column.key === 'vipStatus'">
              <a-tag
                v-if="record.vipExpireTime && new Date(record.vipExpireTime) > new Date()"
                color="gold"
              >
                VIP用户
              </a-tag>
              <a-tag v-else color="default"> 普通用户 </a-tag>
            </template>

            <!-- 创建时间列 -->
            <template v-else-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="viewUser(record)">
                  <EyeOutlined />
                  查看
                </a-button>
                <a-button type="link" size="small" @click="editUser(record)">
                  <EditOutlined />
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这个用户吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteUser(record.id)"
                >
                  <a-button type="link" size="small" danger>
                    <DeleteOutlined />
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalType === 'add' ? '添加用户' : '编辑用户'"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="modalLoading"
    >
      <a-form ref="modalFormRef" :model="modalForm" :rules="modalRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户账号" name="userAccount">
              <a-input
                v-model:value="modalForm.userAccount"
                placeholder="请输入用户账号"
                :disabled="modalType === 'edit'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户名" name="userName">
              <a-input v-model:value="modalForm.userName" placeholder="请输入用户名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="modalForm.email" placeholder="请输入邮箱" type="email" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户角色" name="userRole">
              <a-select v-model:value="modalForm.userRole" placeholder="请选择用户角色">
                <a-select-option value="user">普通用户</a-select-option>
                <a-select-option value="admin">管理员</a-select-option>
                <a-select-option value="vip">VIP用户</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item v-if="modalType === 'add'" label="密码" name="userPassword">
          <a-input-password v-model:value="modalForm.userPassword" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item label="头像URL" name="userAvatar">
          <a-input v-model:value="modalForm.userAvatar" placeholder="请输入头像URL" />
        </a-form-item>

        <a-form-item label="个人简介" name="userProfile">
          <a-textarea
            v-model:value="modalForm.userProfile"
            placeholder="请输入个人简介"
            :rows="3"
          />
        </a-form-item>

        <a-row :gutter="16" v-if="modalType === 'edit'">
          <a-col :span="12">
            <a-form-item label="VIP到期时间" name="vipExpireTime">
              <a-date-picker
                v-model:value="modalForm.vipExpireTime"
                placeholder="请选择VIP到期时间"
                style="width: 100%"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="VIP次数" name="vipNumber">
              <a-input-number
                v-model:value="modalForm.vipNumber"
                placeholder="请输入VIP次数"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 查看用户详情弹窗 -->
    <a-modal v-model:open="viewModalVisible" title="用户详情" width="500px" :footer="null">
      <div v-if="viewUserData" class="user-detail">
        <div class="detail-item">
          <div class="detail-avatar">
            <a-avatar :src="viewUserData?.userAvatar" :size="80">
              <template #icon><UserOutlined /></template>
            </a-avatar>
          </div>
        </div>

        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="用户ID">{{ viewUserData?.id }}</a-descriptions-item>
          <a-descriptions-item label="用户账号">{{
            viewUserData?.userAccount
          }}</a-descriptions-item>
          <a-descriptions-item label="用户名">{{ viewUserData?.userName }}</a-descriptions-item>
          <a-descriptions-item label="邮箱">{{ viewUserData?.email }}</a-descriptions-item>
          <a-descriptions-item label="用户角色">
            <a-tag :color="getRoleColor(viewUserData?.userRole)">
              {{ getRoleText(viewUserData?.userRole) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="个人简介">{{
            viewUserData?.userProfile || '暂无'
          }}</a-descriptions-item>
          <a-descriptions-item label="VIP状态">
            <a-tag
              v-if="
                viewUserData?.vipExpireTime && new Date(viewUserData.vipExpireTime) > new Date()
              "
              color="gold"
            >
              VIP用户 (到期: {{ formatDate(viewUserData.vipExpireTime) }})
            </a-tag>
            <a-tag v-else color="default">普通用户</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="VIP次数">{{
            viewUserData?.vipNumber || 0
          }}</a-descriptions-item>
          <a-descriptions-item label="邀请码">{{ viewUserData?.shareCode }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{
            formatDate(viewUserData?.createTime)
          }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{
            formatDate(viewUserData?.updateTime)
          }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import {
  listUserByPage,
  addUser,
  updateUser,
  deleteUser as deleteUserApi,
  getUserById
} from '@/api/guanliyuanjiekou'
import type { Rule } from 'ant-design-vue/es/form'
import type { TableColumnsType, TableProps } from 'ant-design-vue'

// 响应式数据
const loading = ref(false)
const userList = ref<API.UserAdminVO[]>([])
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const modalFormRef = ref()
const viewUserData = ref<API.UserAdminVO>()

// 搜索表单
const searchForm = reactive<API.UserQueryDTO>({
  pageNum: 1,
  pageSize: 10,
  userAccount: '',
  userName: '',
  email: '',
  userRole: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 弹窗表单
const modalForm = reactive<API.UserAddDTO & API.UserUpdateAdminDTO>({
  userAccount: '',
  userName: '',
  email: '',
  userRole: 'user',
  userPassword: '',
  userAvatar: '',
  userProfile: '',
  vipExpireTime: undefined,
  vipNumber: 0
})

// 表单验证规则
const modalRules: Record<string, Rule[]> = {
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 4, message: '用户账号长度不能少于4个字符', trigger: 'blur' }
  ],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  userRole: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
}

// 表格列配置
const columns: TableColumnsType = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    fixed: 'left'
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar',
    width: 80,
    align: 'center'
  },
  {
    title: '用户账号',
    dataIndex: 'userAccount',
    key: 'userAccount',
    width: 120
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 120
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 200
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    key: 'userRole',
    width: 100,
    align: 'center'
  },
  {
    title: 'VIP状态',
    key: 'vipStatus',
    width: 100,
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center'
  }
]

// 方法
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }

    const res = await listUserByPage(params)

    if (res.data.code === 200 && res.data.data) {
      userList.value = res.data.data.records || []
      pagination.total = res.data.data.totalRow || 0
    } else {
      message.error(res.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败：', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 10,
    userAccount: '',
    userName: '',
    email: '',
    userRole: undefined
  })
  pagination.current = 1
  fetchUserList()
}

const handleTableChange: TableProps['onChange'] = pag => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  fetchUserList()
}

const showAddModal = () => {
  modalType.value = 'add'
  modalVisible.value = true
  resetModalForm()
}

const editUser = (record: API.UserAdminVO) => {
  modalType.value = 'edit'
  modalVisible.value = true
  Object.assign(modalForm, {
    ...record,
    vipExpireTime: record.vipExpireTime ? dayjs(record.vipExpireTime) : undefined
  })
}

const viewUser = async (record: API.UserAdminVO) => {
  try {
    const res = await getUserById({ id: record.id! })
    if (res.data.code === 200 && res.data.data) {
      viewUserData.value = res.data.data
      viewModalVisible.value = true
    } else {
      message.error(res.data.message || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败：', error)
    message.error('获取用户详情失败')
  }
}

const deleteUser = async (id: string) => {
  try {
    const res = await deleteUserApi({ id })
    if (res.data.code === 200) {
      message.success('删除用户成功')
      fetchUserList()
    } else {
      message.error(res.data.message || '删除用户失败')
    }
  } catch (error) {
    console.error('删除用户失败：', error)
    message.error('删除用户失败')
  }
}

const handleModalOk = async () => {
  try {
    await modalFormRef.value.validate()
    modalLoading.value = true

    const formData = {
      ...modalForm,
      vipExpireTime: modalForm.vipExpireTime
        ? (modalForm.vipExpireTime as unknown as Dayjs).format('YYYY-MM-DD HH:mm:ss')
        : undefined
    }

    if (modalType.value === 'add') {
      const res = await addUser(formData as API.UserAddDTO)
      if (res.data.code === 200) {
        message.success('添加用户成功')
        modalVisible.value = false
        fetchUserList()
      } else {
        message.error(res.data.message || '添加用户失败')
      }
    } else {
      const res = await updateUser(formData as API.UserUpdateAdminDTO)
      if (res.data.code === 200) {
        message.success('更新用户成功')
        modalVisible.value = false
        fetchUserList()
      } else {
        message.error(res.data.message || '更新用户失败')
      }
    }
  } catch (error) {
    console.error('操作失败：', error)
  } finally {
    modalLoading.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetModalForm()
}

const resetModalForm = () => {
  Object.assign(modalForm, {
    userAccount: '',
    userName: '',
    email: '',
    userRole: 'user',
    userPassword: '',
    userAvatar: '',
    userProfile: '',
    vipExpireTime: undefined,
    vipNumber: 0
  })
  modalFormRef.value?.resetFields()
}

const getRoleColor = (role?: string) => {
  switch (role) {
    case 'admin':
      return 'red'
    case 'vip':
      return 'gold'
    default:
      return 'blue'
  }
}

const getRoleText = (role?: string) => {
  switch (role) {
    case 'admin':
      return '管理员'
    case 'vip':
      return 'VIP用户'
    default:
      return '普通用户'
  }
}

const formatDate = (dateString?: string) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manager {
  background: #f5f5f5;
  min-height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
}

.page-header {
  padding: 24px 0 0 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 16px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.search-section {
  padding: 24px 0 0 0;
}

.search-section .ant-card {
  border-radius: 0;
  border-left: none;
  border-right: none;
  width: 100%;
}

.search-form {
  padding: 8px 24px;
  width: 100%;
  box-sizing: border-box;
}

.table-section {
  padding: 0;
}

.table-section .ant-card {
  border-radius: 0;
  border-left: none;
  border-right: none;
  border-bottom: none;
  width: 100%;
}

.user-detail {
  padding: 16px 0;
}

.detail-item {
  margin-bottom: 24px;
}

.detail-avatar {
  text-align: center;
  margin-bottom: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 16px 16px 0 16px;
  }

  .search-section {
    padding: 16px;
  }

  .table-section {
    padding: 0 16px 16px 16px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .ant-form-item {
    margin-bottom: 16px;
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-modal-body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
